using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Security;
using System.IO;
using System.ServiceProcess;
using System.Net.Mail;
using System.Collections;

namespace ExchangeDaemon
{
    public partial class UserWindow : Form
    {
        public IList<string> Data;
        public Hashtable Settings;

        private IList<string> Before = new List<string>();
        private IList<string> After = new List<string>();

        public UserWindow()
        {
            LoadSettings();
            String path = System.Reflection.Assembly.GetExecutingAssembly().Location;
            path = System.IO.Path.GetDirectoryName(path);
            Directory.SetCurrentDirectory(path);
            InitializeComponent();
            Data = new List<string>();
            dataGridView1.Rows.Add();
            dataGridView1.Rows.Add();
            string[] columns = ((string)this.Settings["DataColumns"]).Split(';');
            foreach (string s in columns)
            {
                System.Windows.Forms.DataGridViewTextBoxColumn col = new System.Windows.Forms.DataGridViewTextBoxColumn();
                col.HeaderText = s;
                this.dataGridView1.Columns.Add(col);
            }
            LoadFiles();
        }

        private void LoadFiles()
        {
            string[] filenames = Directory.GetFiles(Directory.GetCurrentDirectory() + "\\pending");
            foreach (string file in filenames)
            {
                try
                {
                    FileStream fs = File.Open(file, FileMode.Open);
                    StreamReader sr = new StreamReader(fs);
                    string line = sr.ReadLine();
                    AddRow(line);
                    Before.Add(line);
                    sr.Close();
                    fs.Close();
                }
                catch
                {
                    MessageBox.Show("Nie mozna otworzyc pliku. Inny proces uzywa tego pliku");
                }
            }
        }

        private void OK_Click(object sender, EventArgs e)
        {
            for (int j = 0; j < dataGridView1.Rows.Count; j++)
            {
                DataGridViewCheckBoxCell cell = new DataGridViewCheckBoxCell();
                if(dataGridView1.Rows[j].Cells[1].Value == null && ((DataGridViewCheckBoxCell)dataGridView1.Rows[j].Cells[0]).Value != cell.TrueValue)
                {
                    MessageBox.Show("Nalezy wskazac typ tworzonego obiektu (user/contact)");
                    return;
                }
            }
            string[] filenames = Directory.GetFiles(Directory.GetCurrentDirectory() + "\\pending");
            int i = 0;
            foreach(string file in filenames)
            {
                FileStream fs = File.Open(file, FileMode.Open);
                string line = this.GetDataFromRow(i);
                if (line != null)
                {
                    After.Add(line);
                    StreamWriter sw = new StreamWriter(fs);
                    sw.WriteLine(line);
                    sw.Close();
                    fs.Close();
                }
                else
                {
                    After.Add("CANCEL");
                    fs.Close();
                    string[] temp = file.Split('\\');
                    File.Move(file, Directory.GetCurrentDirectory() + "\\arch\\" + temp[temp.Length - 1]);
                }
                
                i++;
            }
            string Mail = CompareLists(Before, After);
            SaveMail(Mail);
            ServiceController Controller = new ServiceController("CISExchangeDaemonService");
            if (Controller.Status == ServiceControllerStatus.Running)
            {
                Controller.ExecuteCommand(128);
            } 
            Application.Exit();
        }

        public void AddRow(string csv_data)
        {
            string[] temp = csv_data.Split(';');
            int i = 2;
            foreach(string s in temp)
            {
                try
                {
                    dataGridView1.Rows[dataGridView1.Rows.Count - 2].Cells[i].Value = s;
                    i++;
                }
                catch
                {
                    MessageBox.Show("Przeslane dane nie sa zgodne ze skonfigurowanym wzorem. Wzor jest nastepujacej postaci: \n " + this.Settings["DataColumns"] + "\n");
                    SendMail(this.Settings["FromMail"] as string, this.Settings["CISMail"] as string, "Decyzje dotyczace kont Exchange", "Dane " + csv_data + "nie pasuja do wzorca na serwerze. Skontaktuj sie z administratorem exchange w celu ustalenia obowiazujacego wzorca", false);
                }
            }
            dataGridView1.Rows.Insert(dataGridView1.Rows.Count - 1, 1);
        }

        private string GetDataFromRow(int j)
        {
            StringBuilder sb = new StringBuilder();
            DataGridViewCheckBoxCell cell = new DataGridViewCheckBoxCell();
            if (((DataGridViewCheckBoxCell)dataGridView1.Rows[j].Cells[0]).Value != cell.TrueValue)
            {
                for (int i = 1; i < dataGridView1.Rows[j].Cells.Count; i++)
                {
                    sb.Append(dataGridView1.Rows[j].Cells[i].Value + ";");
                }
                return sb.ToString().Substring(0, sb.ToString().Length - 1);
            }
            else return null;
        }

        private void Cancel_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private static string CompareLists(IList<string> before, IList<string> after)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("WIADOMOSC WYGENEROWANA AUTOMATYCZNIE\n");
            sb.Append("=================++++++++++=================\n");
            for (int i = 0; i < before.Count; i++)
            {
                string[] temp = after[i].Split(';');
                StringBuilder new_line = new StringBuilder();
                for (int k = 1; k < temp.Length; k++)
                {
                    new_line.Append(temp[k] + ";");
                }
                string after_string;
                try
                {
                    after_string = new_line.ToString().Substring(0, new_line.ToString().Length - 1);
                }
                catch
                {
                    after_string = "CANCEL";
                }
                sb.Append("Konto uzytkownika: " + (before[i].Split(';'))[0] + " " +(before[i].Split(';'))[1] + "\n");
                if (before[i].Replace(";", "").Equals(after_string.Replace(";", "")))
                {
                    sb.Append("Dane nie ulegly zmianie\n");
                }
                else
                {
                    if (after[i].Equals("CANCEL"))
                    {
                        sb.Append("Konto nie zostalo zaakceptowane\n");
                    }
                    else
                    {
                        sb.Append("Dane zmieniono:\n");
                        string[] before_temp = before[i].Split(';');
                        string[] after_temp = after[i].Split(';');
                        for (int j = 0; j < before_temp.Length; j++)
                        {
                            if (!before_temp[j].Equals(after_temp[j+1]))
                            {
                                sb.Append(before_temp[j] + " na " + after_temp[j] + "\n");
                            }
                        }
                    }
                }
                sb.Append("++++++++++++++++++++++++++++++++++++\n");
            }
            return sb.ToString();
        }

        private static void SaveMail(string body)
        {
            MailForm win = new MailForm(body);
            if (win.ShowDialog() == DialogResult.OK)
            {
                FileStream fs = File.Create(Directory.GetCurrentDirectory() + "\\mail");
                StreamWriter sw = new StreamWriter(fs);
                sw.Write(win.Mail);
                sw.Close();
                fs.Close();
            }
        }

        private static void SendMail(string fromEmail, string toEmail, string subject, string body, bool editable)
        {
            SmtpClient MyMail = new SmtpClient("127.0.0.1");
            MyMail.DeliveryMethod = SmtpDeliveryMethod.Network;
            MyMail.Send(fromEmail, toEmail, subject, body);
        }

        private void LoadSettings()
        {
            Settings = new Hashtable();
            String path = System.Reflection.Assembly.GetExecutingAssembly().Location;
            path = System.IO.Path.GetDirectoryName(path);
            Directory.SetCurrentDirectory(path);
            string filename = Directory.GetCurrentDirectory() + "\\CIS Exchange Daemon.config";

            try
            {
                FileStream fs;
                fs = File.Open(filename, FileMode.Open, FileAccess.Read);
                StreamReader sr = new StreamReader(fs);
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    try
                    {
                        string[] temp = line.Split('=');
                        Settings.Add(temp[0], temp[1]);
                    }
                    catch
                    {
                        MessageBox.Show("Blad przyczytaniu pliku konfiguracyjnego");
                        Application.Exit();
                    }
                }
                sr.Close();
                fs.Close();
            }
            catch
            {
                MessageBox.Show("Blad przyczytaniu pliku konfiguracyjnego");
                Application.Exit();
            }
        }
    }
}